package com.peng.community.quartz;

import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.DiscussPost;
import com.peng.community.service.CommentService;
import com.peng.community.service.DiscussPostService;
import com.peng.community.service.impl.ElasticSearchService;
import com.peng.community.service.impl.LikeService;
import com.peng.community.util.RedisKeyUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PostScoreRefreshJob implements Job, CommunityConstant {

    private static Logger log = LoggerFactory.getLogger(PostScoreRefreshJob.class);

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    CommentService commentService;

    @Autowired
    LikeService likeService;

    @Autowired
    ElasticSearchService elasticSearchService;

    //牛客纪元
    private static Date epoch;

    static {
        try {
            epoch = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2014-08-01 00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
            log.error("获取牛客纪元出现异常");
        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        BoundSetOperations setOps = redisTemplate.boundSetOps(postScoreKey);
        if (setOps.size() == 0) {
            //当前时间段没有活跃的帖子
            log.info("[任务取消，没有活跃的帖子]");
            return;
        }
        log.info("[任务开始]");

        while (setOps.size() > 0) {
            refresh((int)setOps.pop());
        }

        log.info("[任务结束]");
    }

    //更新此id对应的帖子的热度
    public void refresh(int postId) {
        DiscussPost discussPost = discussPostService.findDiscussPostById(postId);
        if (discussPost == null) {
            log.error("id为{}的帖子不存在", postId);
            return;
        }
        //计算帖子的分数

        boolean isWonderful = discussPost.getStatus() == 1;
        int commentCount = discussPost.getCommentCount();
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, postId);

        //计算权重
        long w = (isWonderful ? 75 : 0) + commentCount * 10 + likeCount * 2;

        //帖子分数 = 权重 + 距离天数
        long score = w + (discussPost.getCreateTime().getTime() - epoch.getTime()) / (1000 * 3600 * 24);

        discussPostService.updateScore(postId,score);

        //更新ES的数据
        discussPost.setScore(score);
        elasticSearchService.save(discussPost);
    }
}
